import { useState, useEffect } from 'react';
import { Form, Input, Button, Card, Space, Alert } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Redirect } from 'react-router-dom';

import styles from './index.module.scss';

import Apis from '../../../api';
import auth from '../../../page/auth';

const { HTTPError } = Apis.error;

function PageUserLogin() {
  const [form] = Form.useForm();
  const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
  const [authenticated, setAuthenticated] = useState<boolean>(false);

  const onReset = () => {
    form.resetFields();
  };
  const onFinish = async (values: any) => {
    const username = values.username as string;
    const password = values.password as string;

    try {
      await auth.login(username, password);
    } catch (err) {
      if (err instanceof HTTPError) {
        const resp = await err.response.json();
        setErrorMessage(resp.msg);
      } else {
        setErrorMessage('服务器开小差了');
        console.error(err);
      }
    }
  };

  useEffect(() => {
    auth.user.subscribe(({ authenticated }) => {
      setAuthenticated(authenticated);
    });
  }, [authenticated]);

  if (authenticated) {
    return <Redirect to="/" />;
  } else
    return (
      <Card className={styles['login-form']}>
        <Form form={form} layout="vertical" size="large" onFinish={onFinish}>
          <Form.Item name="username" label="用户名" required tooltip="用户名">
            <Input placeholder="请填写用户名" />
          </Form.Item>
          <Form.Item name="password" label="密码" required tooltip={{ title: '密码', icon: <InfoCircleOutlined /> }}>
            <Input type="password" placeholder="请填写密码" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button onClick={onReset}>重置</Button>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Space>
          </Form.Item>
          {errorMessage && (
            <Alert message={errorMessage} showIcon closable type="error" onClose={() => setErrorMessage(undefined)} />
          )}
        </Form>
      </Card>
    );
}

export default PageUserLogin;
